#include <stdio.h>
#include <string.h>
#include <stdlib.h>

//sscanf 只要第一个字符匹配不上就退出

//%*s或%*d 跳过数据
void test01()
{
#if 0
    char *str = "12345abcde";
    char buf[1024] = {0};

    sscanf(str, "%*d%s",buf);
    printf("buf:%s\n", buf); //buf:abcde
#else
    char *str =  "abcde 12345";
    char buf[1024] = { 0 };

    //忽略字符串到空格或者\t
    sscanf(str, "%*s%s", buf);
    printf("buf:%s\n", buf); //buf:12345
#endif
}

//%[width]s 读指定宽度的数据
void test02()
{
    char *str = "12345abcde";
    char buf[1024] = {0};

    sscanf(str, "%7s",buf);
    printf("buf:%s\n", buf); //buf:12345ab
}

//%[a-z] 匹配a到z中的任意字符(尽可能多的匹配)
void test03()
{
    char *str = "12345abcde";
    char buf[1024] = {0};

    sscanf(str, "%*d%[a-c]",buf);
    printf("buf:%s\n", buf); //buf:abc
}

//%[aBc] 匹配a、B、c中一员 贪婪性
void test04()
{
    char *str = "aABbcde";
    char buf[1024] = {0};

    sscanf(str, "%[aAb]",buf);
    printf("buf:%s\n", buf); //buf:aA
}

//%[^a] 匹配非a的任意字符, 贪婪性
void test05()
{
    char *str = "aABbcde";
    char buf[1024] = {0};

    sscanf(str, "%[^c]",buf);
    printf("buf:%s\n", buf); //buf:aABb
}

//%[^a-z] 表示读取除a-z以外的所有字符
void test06()
{
    char *str = "aABbcde12345";
    char buf[1024] = {0};

    sscanf(str, "%[^0-9]",buf);
    printf("buf:%s\n", buf); //buf:aABbcde
}

void test07()
{
    char *ip = "127.0.0.1";
    int num1 = 0, num2 = 0, num3 = 0, num4 = 0;

    sscanf(ip,"%d.%d.%d.%d",&num1,&num2,&num3,&num4);
    printf("num1:%d\n",num1); //num1:127
    printf("num2:%d\n",num2);//num2:0
    printf("num3:%d\n",num3);//num3:0
    printf("num4:%d\n",num4);//num4:1
}

void test08()
{
    char* str = "abcde#12uiop@0plju";
    char buf[1024] = { 0 };
    sscanf(str, "%*[^#]#%[^@]", buf);
    printf("buf:%s\n",buf);
}

int main(int argc, char const *argv[])
{
    test01();
    test02();
    test03();
    test04();
    test05();
    test06();
    test07();
    test08();
    return 0;
}
